const puppeteer = require('puppeteer');
const request = require('request');
const fs = require('fs');
const xlsx = require('node-xlsx');
const randomName = require('random-name');
const GoLogin = require('gologin');
const setting = require('./setting');

(async () => {

  let simCountry = 'india';
  let proxy = setting.proxy;
  const sheets = xlsx.parse(setting.excelPath);
  let isFinish = false;
  let GL;
  let browser;
  for (let number = 1; number < 15; number++) {
    let interval;
    try {
      isFinish = false;
      let sheetElement = sheets[0].data[number];
      console.log('sheets data：', sheetElement);
      const firstName = sheetElement[0];
      const lastName = sheetElement[1];
      const mail = sheetElement[2];
      const password = sheetElement[3];
      const birthday = sheetElement[4];
      let date = new Date(1900, 0, birthday - 1);
      console.log(date.toLocaleDateString());
      const birthday_day = date.getDate().toString();
      const birthday_month = date.getMonth() + 1;
      const birthday_year = date.getFullYear().toString();

      const gender = sheetElement[5].toUpperCase();
      const p_gender = gender === 'FEMALE' ? 2 : 1;
      const rMail = sheetElement[6];
      const profileId = sheetElement[7];

      GL = new GoLogin({
        token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2MzgyMjYxYmJhNjczZWQ2YjU0NTU5NzYiLCJ0eXBlIjoiZGV2Iiwiand0aWQiOiI2NDU0NzlhYzdhZWEzMmVmOWY3Mjk3ZGUifQ.f1Kj2S6iqgKGA5Oep_mfMWiPktEvOP5ZYWnUlF7f3Og',
        profile_id: profileId,
        extra_params: ['--start-maximized', '--proxy-server=socks5://' + proxy],
        uploadCookiesToServer: true,
        writeCookesFromServer: true,
      });
      setting.getProxy();
      const { status, wsUrl } = await GL.start();

      browser = await puppeteer.connect({
        browserWSEndpoint: wsUrl.toString(),
        ignoreHTTPSErrors: true,
      });
      const page = await browser.newPage();
      await page.setViewport({ width: 1920, height: 1080 });
      page.setDefaultNavigationTimeout(0);
      page.setDefaultTimeout(0);
      console.log('打开注册网站');
      await page.goto('https://accounts.google.com/signup');
      interval = setInterval(function () {
        GL.uploadProfileCookiesToServer();
      }, 20000);

      let $firstName = await page.waitForSelector('#firstName');
      await $firstName.type(firstName, { delay: 100 });

      let $lastName = await page.waitForSelector('#lastName');
      await $lastName.type(lastName, { delay: 100 });

      let $username = await page.waitForSelector('#username');
      await $username.click({ clickCount: 4 });
      await page.keyboard.press('Backspace');
      await $username.type(mail, { delay: 100 });

      let $pass = await page.waitForSelector('input[name=Passwd]');
      await $pass.type(password, { delay: 100 });

      let $comfirmPass = await page.waitForSelector('input[name=ConfirmPasswd]');
      await $comfirmPass.type(password, { delay: 100 });

      let $checkBox = await page.waitForSelector('input[type=checkBox]');
      await $checkBox.click({ delay: 100 });

      let $accountDetailsNext = await page.waitForSelector('#accountDetailsNext');
      await $accountDetailsNext.click({ delay: 100 });

      function intervalRequestCode() {
        console.log('开始获取注册电话');
        let t1 = new Date();
        request.get('https://5sim.net/v1/user/buy/activation/' + simCountry + '/any/google', {
          json: true,
          headers: {
            Authorization: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2MzgyMjYxYmJhNjczZWQ2YjU0NTU5NzYiLCJ0eXBlIjoiZGV2Iiwiand0aWQiOiI2NDU0NzlhYzdhZWEzMmVmOWY3Mjk3ZGUifQ.f1Kj2S6iqgKGA5Oep_mfMWiPktEvOP5ZYWnUlF7f3Og',
            Accept: 'application/json',
          },
        }, async (err, res, body) => {
          try {
            if (err) {
              console.log('注册电话获取失败');
              return console.log(err);
            }
            let text = body.phone;
            if (text != null) {
              console.log('注册电话获取成功');
              let phoneNumberId = await page.waitForSelector('#phoneNumberId', { visible: true });
              await phoneNumberId.click({ clickCount: 3, delay: 100 });
              await page.keyboard.press('Backspace');

              await phoneNumberId.type(text, { delay: 100 });
              let $VfPpkd = await page.waitForSelector('.VfPpkd-vQzf8d', { visible: true });
              await $VfPpkd.click();

              console.log(body.phone, body.id);

              function intervalGetCode() {
                console.log('获取注册验证码');
                request.get('https://5sim.net/v1/user/check/' + body.id, {
                  json: true,
                  headers: {
                    Authorization: 'Bearer eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NjM0OTA0NDMsImlhdCI6MTYzMTk1NDQ0MywicmF5IjoiYTNjYjNkNjdhOTRhY2MyNTYwYWEwNTIwYWFjOGIzNDIiLCJzdWIiOjYyMDcxOX0.lvSnnpVPrMYg-eQOZ-FEF6yWUkBBQAvqPGXs_l-KvKa12q5cYNMJM82O5uUbfcSJXkfXrLRlmk6oV52d55Id2gva-0MlnASVCaS-FnWi0VxW_2QLe9QX9MX_d0VqGO6J3-NL9VvoncsSUwy53NiSDMsT0UcUkhiqagNPTnByZf1a3CJQ5RS_IdL9BCOh46J6YGh7jTWpIEs_oOBn_IHRSDcU75EIFTBWjDGGki_2udjwtHpNKTw0qB9yuUrFxCvL_6-wkjAFn4dMHbQeglKHZR6MZQf-fKLfQqsCZiUbzohScbPuvT1cUcqr67V9AJQt6r6yo10ZfowGIw-heVVWCA',
                    Accept: 'application/json',
                  },
                }, async (err, res, body) => {
                  try {
                    if (err) {
                      console.log('注册验证码获取失败');
                      return console.log(err);
                    }
                    console.log(body.phone);
                    let sms = body.sms;
                    if (sms != null && sms.length > 0) {
                      console.log('注册验证码获取成功');
                      let message = sms[0].code;
                      console.log(message);
                      if (message) {
                        clearInterval(this);
                        let $Xb9hP = await page.waitForSelector('.Xb9hP');

                        const code = await page.$('.zHQkBf');
                        await code.type(message);
                        await (await page.$('.nCP5yc')).click({ clickCount: 2 });
                        await sleep(1000 + Math.random() * 2000);

                        let phoneNumberId = await page.waitForSelector('#phoneNumberId', { visible: true });
                        if (phoneNumberId != null) {
                          await phoneNumberId.click({ clickCount: 4 });
                          await page.waitForTimeout(1000);
                          await page.keyboard.press('Backspace');
                          await phoneNumberId.click({ clickCount: 4 });
                          await page.waitForTimeout(1000);
                          await page.keyboard.press('Backspace');
                        }

                        let $mail = await page.waitForSelector('input[type=email]', { visible: true });
                        await $mail.click({ clickCount: 4 });
                        await page.keyboard.press('Backspace');
                        await $mail.type(rMail);

                        const day = await page.$('input[name=day]');
                        await day.type(birthday_day, { delay: 100 });

                        await page.select('#month', birthday_month.toString());//选择下拉框内容

                        const year = await page.$('input[name=year]');
                        await year.type(birthday_year, { delay: 100 });

                        await page.select('#gender', p_gender.toString());//选择下拉框内容

                        let phoneNumberId2 = await page.$('#phoneNumberId');
                        await phoneNumberId2.click({ clickCount: 4 });
                        await page.keyboard.press('Backspace');

                        let $Jh9lGc = await page.waitForSelector('.VfPpkd-Jh9lGc');
                        await $Jh9lGc.click({ delay: 1000 });

                        let $UbuQg = await page.waitForSelector('.VfPpkd-LgbsSe-OWXEXe-Bz112c-UbuQg', { visible: true });
                        await autoScroll(page);
                        await $UbuQg.click({ delay: 500 });

                        let $X2Tq4cdisableButton = await page.waitForSelector('#X2Tq4cdisableButton');
                        await $X2Tq4cdisableButton.click({ delay: 500 });
                        let $JQjcvcdisableButton = await page.waitForSelector('#JQjcvcdisableButton');
                        await $JQjcvcdisableButton.click({ delay: 500 });
                        let $Ef1uXedisableButton = await page.waitForSelector('#Ef1uXedisableButton');
                        await $Ef1uXedisableButton.click({ delay: 500 });
                        let $VfPpkd1 = await page.waitForSelector('.VfPpkd-LgbsSe-OWXEXe-k8QpJ');
                        await $VfPpkd1.click({ delay: 500, timeout: 0 });
                        await page.waitForSelector('.x7WrMb', { timeout: 0 });
                        try {
                          await GL.uploadProfileCookiesToServer();
                          const page2 = await browser.newPage();
                          await page2.setViewport({ width: 1920, height: 1080 });
                          await page2.goto('https://google.com', { timeout: 0 });
                          page2.waitForTimeout(2000);
                          clearInterval(interval);
                          await browser.close();
                          await GL.stop();
                          isFinish = true;
                        } catch (e) {
                          console.log(e);

                          await browser.close();
                          await GL.stop();
                          isFinish = true;
                        }

                      }
                    } else {
                      console.log('未收到验证码', '验证码获取时间', (new Date().getTime() - t1) + '');
                      let crtElement = await page.$('.jibhHc');
                      if ((new Date().getTime() - t1) > 90000 || crtElement != null) {
                        console.log('验证码获取超时');
                        clearInterval(this);
                        request.get('https://5sim.net/v1/user/cancel/' + body.id, {
                          json: true,
                          headers: {
                            Authorization: 'Bearer eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NjM0OTA0NDMsImlhdCI6MTYzMTk1NDQ0MywicmF5IjoiYTNjYjNkNjdhOTRhY2MyNTYwYWEwNTIwYWFjOGIzNDIiLCJzdWIiOjYyMDcxOX0.lvSnnpVPrMYg-eQOZ-FEF6yWUkBBQAvqPGXs_l-KvKa12q5cYNMJM82O5uUbfcSJXkfXrLRlmk6oV52d55Id2gva-0MlnASVCaS-FnWi0VxW_2QLe9QX9MX_d0VqGO6J3-NL9VvoncsSUwy53NiSDMsT0UcUkhiqagNPTnByZf1a3CJQ5RS_IdL9BCOh46J6YGh7jTWpIEs_oOBn_IHRSDcU75EIFTBWjDGGki_2udjwtHpNKTw0qB9yuUrFxCvL_6-wkjAFn4dMHbQeglKHZR6MZQf-fKLfQqsCZiUbzohScbPuvT1cUcqr67V9AJQt6r6yo10ZfowGIw-heVVWCA',
                            Accept: 'application/json',
                          },
                        }, async (err, res, body) => {

                        });
                        let $jibhHc = await page.waitForSelector('.lw1w4b');
                        await $jibhHc.click();
                        intervalRequestCode();
                      }
                    }
                  } catch (e) {
                    console.log(e);
                    await GL.uploadProfileCookiesToServer();
                  }
                });
              }

              setInterval(intervalGetCode, 4000);
            } else {
              console.log('注册电话获取失败');
              intervalRequestCode();
            }
          } catch (e) {
            console.log(e);
          }
          await GL.uploadProfileCookiesToServer();

        });
      }

      intervalRequestCode();
    } catch (e) {
      console.log(e);
      isFinish = true;
      await browser.close();
      await GL.stop();
    }

    while (!isFinish) {
      await sleep(6000);
    }
  }

})();

async function autoScroll(page) {
  await page.evaluate(async () => {
    await new Promise((resolve, reject) => {
      let totalHeight = 0;
      let distance = 100;
      let timer = setInterval(() => {
        let scrollHeight = document.body.scrollHeight;
        window.scrollBy(0, distance);
        totalHeight += distance;

        if (totalHeight >= scrollHeight) {

          clearInterval(timer);
          resolve();
        }
      }, 120);
    });
  });
}

async function clickElm(page, str) {
  await page.waitForSelector(str);
  let crtElement = await page.$(str);
  let crtBox = await crtElement.boundingBox();
  if (crtBox) {
    let xBox = crtBox.x + (crtBox.width * 2 / 3) * Math.random();
    let yBox = crtBox.y + (crtBox.height * 2 / 3) * Math.random();
    await page.mouse.move(xBox, yBox);
    await page.mouse.click(xBox, yBox, { delay: 800 + Math.random() * 1000 });
  }
}

function sleep(ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
}
